/**
 * Save personal settings thru ajax
 * Settings are loaded by module name
 * Stored in one object Storage{ Module-1, Module-2, ... }
 * Unlimited settings under each module
 * 
 * pref = new ig_prefs(namespace,setting_name); // settings_name='' - key name in DB
 */

function ig_prefs(section_name, settings_name) {

  // these 2 not implemented here
  this.get_url='';
  this.save_url='';

  this.use = function(name) {
  if (this.error) return;
	this._makeStorage(name);
	this._setCurrent(name);
	this.using = name;
  }

  this.load = function(prefs_name) {

	if (this.error) return;
	if (!prefs_name) {
	  return;
	}

    v='';
	//v = getv(this.get_url, 'param=' + prefs_name, 'post');
	//v = v ? JSON.parse(v) : null;
    

	if (v) this.storage = v;
	else
	this.storage = {};
  }

  this.save = function(cleanup,v) {
	if (this.error) return;
	no_v=typeof v==='undefined';

	if (cleanup&&no_v) this.cleanup();
	if(cleanup&&!no_v) this.set(cleanup,v);
	
	// encode your data here and send to save
	//data = json_encode(this.storage);


  }


  this._getProperty = function(path, obj) {
	if (this.error) return;
	path = path.split(/[\[\]\.]+/);
	curr_obj = obj ? obj : this.obj;
	if (path[path.length - 1] == "") path.pop();
	while (path.length && (curr_obj = curr_obj[path.shift()]));

	return curr_obj;
  }


  this.set = function(path, value) //obj, path, value
  {
	if (!this.using) {
	  this.error = 'Unknown storage use! missing call: prefs.use(\'MyStorageSub\')';
	}
	path = path.replace(/\[|\]/g, '.').replace(/\.+/g, '.');

	if(path[path.length-1]=='.'){
	    path=path.substring(0,path.length-1);
	}
	if (this.error) return;
	var pathElements = path.replace(/\[|\]/g, '.').replace(/\.+/g, '.').split(/\./);
	pathEnd = pathElements[pathElements.length - 1];
	pathRoot = (pathElements.slice(0, pathElements.length - 1).join('.'));

	var currObj = this.obj;
	for (var i = 0; i < pathElements.length; i++) {
	  if (typeof(currObj[pathElements[i]]) == 'undefined') {
	   if(pathElements[i]=='') continue;
		//console.log('creating empty Object: '+pathElements[i]);
		currObj[pathElements[i]] = {};
	  }
	  //console.log('adding to Object: '+pathElements[i]);
	  currObj = currObj[pathElements[i]];
	}

	this._getProperty(pathRoot, this.obj)[pathEnd] = value;
	return true;
  }

  this.remove = function(name) {
	_path = name.split(/\./);
	name = _path.pop();
	_currObj = this.obj;
	for (i in _path) {
	  _currObj = _currObj[_path[i]];
	}


	delete _currObj[name];
  }

  // Remove zero values from properties. NOT called automatically
  // Call yourself on selected path befor saving
  this.cleanup = function(name) {
	if (!name) return;
	path = name.split(/\./);


	currObj = this.obj;
	for (i in path) {
	  currObj = currObj[path[i]];
	}
	to_save = {};
	for (prop in currObj) {
	  if (!currObj[prop]) continue;
	  to_save[prop] = currObj[prop];
	}

	this.set(name, to_save)

  }

/*
   * Search for value by exact path or partial path
   * returns mixed value
   */
  var found = false;
  this.get = function(key) {
	found = false;
	if (this.error) return;
	
	key = key.replace(/\[|\]/g, '.').replace(/\.+/g, '.');

	if(key[key.length-1]=='.'){
	    key=key.substring(0,key.length-1);
	}	
	
	var pathElements = key.replace(/\[|\]/g, '.').replace(/\.+/g, '.').split(/\./);
	_key = (pathElements.join('.'));
	
	//console.log('converted '+key+' to '+_key);
	key=_key;
	
	obj = this.storage[this.using];
	if (!obj) return false;
	this._get(key, obj);
	return found;
  }

  this._get = function(_find, obj) {
	if (this.error) return;
	if (this._getProperty(_find, obj)) {
	  find_path = _find.split(/\./);
	  _obj = obj;
	  while (find_path.length && (_obj = _obj[find_path.shift()]));
	  found = _obj;
	  return;
	}
	for (_prop in obj) {
	  if (_prop === _find) {
		found = obj[_prop];
		return;
	  }
	  if (typeof obj[_prop] === 'object') this._get(_find, obj[_prop]);
	}
  }

  this.available = function() {
	if (!this.storage) return false;
	keys = Object.keys(this.storage);
	return keys;
  }

  this.format = function() {
	this.storage = {};
	this.using = null;
	this.obj = null;
  }

  this._makeStorage = function(name) {
	if (this.error) return;
	if (!this.storage) this.storage = {};
	if (name && !this.storage[name]) {
	  this.storage[name] = {};
	  this._setCurrent(name);
	}
  }

  this._setCurrent = function(name) {
	if (this.error) return;
	this.obj = this.storage[name];
  }

  this.debug = function(name) {
	if (this.error) console.log(this.error);
  }
  // Test availability
  this.test = function() {
	console.log('test call to ' + this.self + ' storage');
	return true;
  }

  //INIT
  this.self = settings_name;
  this.section = section_name ? section_name : '';


  this.load(this.self);
  this.use(this.section);

} //eof ig_prefs



function _set(name, value) {
  if (!this.dataAccess) this.dataAccess = new ig_prefs('dataAccess');
  this.dataAccess.set(name, value);
}

function _get(name, def) {
  if (!this.dataAccess) this.dataAccess = new ig_prefs('dataAccess');
  saved = this.dataAccess.get(name);
  if (!def) def = false;
  return saved ? saved : def;
}



